import cv2
from feature import get_features, get_feature_orb, get_feature_brisk, get_feature_akaze
from pre import preProcess
import os

def list_files_in_directory(folder_path, ignore_filename):
    files = os.listdir(folder_path)
    # 过滤掉指定的文件
    filtered_files = [file for file in files if file != ignore_filename]
    return filtered_files

def feature_match(img1, img2, ratio = 0.9):
    """
    :param img1: 查询图像1
    :param img2: 待匹配的图像2
    :param ratio: 匹配点匹配时，最接近和次接近的比值
    :return matche_img, len(keypoints_raw), len(keypoints_match), len(matches):匹配后图像，原始图像特征点个数，匹配特征点个数，匹配成功的个数
    """
    matcher = cv2.BFMatcher()
    keypoints_raw, descriptors_raw, _, _ = get_features(img1)
    # keypoints_raw, descriptors_raw, _, _ = get_feature_orb(img1)
    # keypoints_raw, descriptors_raw, _, _ = get_feature_akaze(img1)
    # keypoints_raw, descriptors_raw, _, _ = get_feature_brisk(img1)

    keypoints_match, descriptors_match, _, _ = get_features(img2)
    # keypoints_match, descriptors_match, _, _ = get_feature_orb(img2)
    # keypoints_match, descriptors_match, _, _ = get_feature_akaze(img2)
    # keypoints_match, descriptors_match, _, _ = get_feature_brisk(img2)
    raw_matches = matcher.knnMatch(descriptors_raw, descriptors_match, k=2)
    matches = []
    for m1, m2 in raw_matches:
        #  如果最接近和次接近的比值小于一个既定的值，
        #  保留这个最接近的值，认为它和其匹配的点为good_match
        if m1.distance < ratio * m2.distance:
            matches.append([m1])
    matche_img = cv2.drawMatchesKnn(img1, keypoints_raw, img2,
                                    keypoints_match, matches, None, flags=2)
    return matche_img, len(keypoints_raw), len(keypoints_match), len(matches)

if __name__ == '__main__':
    img1 = cv2.imread('./data/test/1_2.tif', cv2.IMREAD_GRAYSCALE)
    img1 = preProcess(img1)
    best_score = 0
    best_name = None
    for file in list_files_in_directory('./data/test/', '1_2.tif'):
        file_name = './data/test/' + file
        img2 = cv2.imread(file_name, cv2.IMREAD_GRAYSCALE)
        img2 = preProcess(img2)
        img_match, img_feature_size, img_match_size, match_size = feature_match(img1, img2)
        print(f'Current recognition file:{file_name}')
        print(f'Raw feature points num:{img_feature_size}')
        print(f'Match Image feature points num:{img_match_size}')
        print(f'Match feature points num:{match_size}')
        score = match_size / min(img_feature_size, img_match_size)
        if score > best_score:
            best_score = score
            best_name = file_name
        print(f'识别率{score}')
        cv2.imshow('img_match', img_match)
        cv2.waitKey(0)
    print(f'最佳匹配文件{best_name},匹配分数{best_score}')
    best_match_img = cv2.imread(best_name, cv2.IMREAD_GRAYSCALE)
    cv2.imshow('Best_match_img', best_match_img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

'''
azka识别正确（0.38，错误0.06）,brisk识别错误，orb识别正确(0.19),sift识别正确(0.41，但错误是0,1)
'''